using System;
using System.IO;
using System.Threading;

public static class Program {
   public static void Main() {
      PollingWithIsCompleted();
      PollingWithAsyncWaitHandle();
   }

public static void PollingWithIsCompleted() {
   // Open the file indicating asynchronous I/O
   FileStream fs = new FileStream(@"C:\Boot.ini", FileMode.Open,
      FileAccess.Read, FileShare.Read, 1024,
      FileOptions.Asynchronous);

   Byte[] data = new Byte[100];

   // Initiate an asynchronous read operation against the FileStream
   IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);

   while (!ar.IsCompleted) {
      Console.WriteLine("Operation not completed; still waiting.");
      Thread.Sleep(10);
   }

   // Get the result. Note: EndRead will NOT suspend this thread
   Int32 bytesRead = fs.EndRead(ar);

   // No other operations to do, close the file
   fs.Close();

   // Now, it is OK to access the byte array and show the result.
   Console.WriteLine("Number of bytes read={0}", bytesRead);
   Console.WriteLine(BitConverter.ToString(data, 0, bytesRead));
}

   public static void PollingWithAsyncWaitHandle() {
      // Open the file indicating asynchronous I/O
      FileStream fs = new FileStream(@"C:\Boot.ini", FileMode.Open,
         FileAccess.Read, FileShare.Read, 1024,
         FileOptions.Asynchronous);

      Byte[] data = new Byte[100];

      // Initiate an asynchronous read operation against the FileStream
      IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);

      while (!ar.AsyncWaitHandle.WaitOne(10, false)) {
         Console.WriteLine("Operation not completed; still waiting.");
      }

      // Get the result. Note: EndRead will NOT suspend this thread
      Int32 bytesRead = fs.EndRead(ar);

      // No other operations to do, close the file
      fs.Close();

      // Now, it is OK to access the byte array and show the result.
      Console.WriteLine("Number of bytes read={0}", bytesRead);
      Console.WriteLine(BitConverter.ToString(data, 0, bytesRead));
   }
}
